<?php
function friends(){
	global $_SGET,$_SPOST,$_SREQUEST;
	global $auid,$valid;
	$id=$_SREQUEST['id'];
	if ($_SERVER['REQUEST_METHOD']=="GET"){
		if (isset($_SREQUEST['id'])){
			$sth = mysql_query("SELECT f2 FROM friends WHERE f1=".$_SREQUEST['id']);
			$res="[";
			while($r = mysql_fetch_assoc($sth)) {
				$res.=$r['f2'].",";
			}
			$sth = mysql_query("SELECT f1 FROM friends WHERE f2=".$_SREQUEST['id']);
			while($r = mysql_fetch_assoc($sth)) {
				$res.= $r['f1'].",";
			}
			$res=rtrim($res,',');
			$res.="]";
			print $res;
		}else{
			header("HTTP/1.0 400 BAD REQUEST");
		}
	}
	/*new friend relation*/
	if ($_SERVER['REQUEST_METHOD']=="POST"){
		if($valid){
			//echo "$id $auid";
			$tmp = mysql_query("SELECT * FROM friendrequests WHERE f1 = '$id' AND f2 = '$auid'");
			if(mysql_num_rows($tmp)){
				$tmp = mysql_fetch_assoc($tmp);
				$id=$_SREQUEST['id'];
				//echo "INSERT INTO `friends` (`id`,`f1`,`f2`) VALUES (NULL,'$auid','$id')";
				$result= @mysql_query("INSERT INTO `friends` (`id`,`f1`,`f2`) VALUES (NULL,'$auid','$id')");
				if (mysql_affected_rows()){
					$tmp = mysql_query("DELETE FROM friendrequests WHERE id='$tmp[id]'");
					header("HTTP/1.0 200 OK");
				}else{
					header("HTTP/1.0 400 BAD REQUEST");
				}
			}else{
				header("HTTP/1.0 400 BAD REQUEST");
			}
		}else{
			header("HTTP/1.0 401 UNAUTHORIZED");
		}
	}
	/*not inplemented*/
	//if ($_SERVER['REQUEST_METHOD']=="PUT"){}

	/*remove friend relation*/
	if ($_SERVER['REQUEST_METHOD']=="DELETE"){
		//echo "hej";
		if($valid){
			$id=$_SREQUEST['id'];
			$query = "DELETE FROM `friends` WHERE (f1=$auid OR f2=$auid) AND (f1=$id OR f2=$id)";
			$result= @mysql_query($query);
			if (mysql_affected_rows()){
				header("HTTP/1.0 200 OK");
			}else{
				header("HTTP/1.0 400 BAD REQUEST");
			}
		}else{
			//echo "<br/>";
			//echo "$auid <br/>";
			//echo "$valid <br>";
			header("HTTP/1.0 401 UNAUTHORIZED");
		}
	}
}
?>